<template>
  <div class="page-container">
	<!--工具栏-->
	<div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;font-weight:normal;">
		<el-form :inline="true" :model="filters" :size="size">
			<el-form-item>
				<kt-button icon="fa fa-plus" label="添加分类" type="primary" @click="handleAdd" />
			</el-form-item>
			<el-form-item>
				<el-input v-model="filters.serviceTypeName" placeholder="分类名称"></el-input>
			</el-form-item>
			<el-form-item>
				<kt-button icon="fa fa-search" :label="$t('action.search')"type="primary" @click="findPage(null)"/>
			</el-form-item>
			<el-form-item>
				<kt-button icon="fa fa-search" label="重置"type="primary"/>
			</el-form-item>
		</el-form>
	</div>
	<div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
		<el-form :inline="true" :size="size">
			<el-form-item>
				<el-button-group>
				<el-tooltip content="刷新" placement="top">
					<el-button icon="fa fa-refresh" @click="findPage(null)">刷新</el-button>
				</el-tooltip>
				<el-tooltip content="列显示" placement="top">
					<el-button icon="fa fa-filter" @click="displayFilterColumnsDialog">列显示</el-button>
				</el-tooltip>
				</el-button-group>
			</el-form-item>
		</el-form>
		<table-column-filter-dialog ref="tableColumnFilterDialog" :columns="columns" 
			@handleFilterColumns="handleFilterColumns"> 
		</table-column-filter-dialog>
	</div>
	<!--表格内容栏-->
	<kt-table :height="350" :data="pageResult" :columns="filterColumns"
		@findPage="findPage"  @handleEdit="handleEdit" @handleStop="handleStop" @handleStart="handleStart" >
	</kt-table>
	<!--新增编辑界面-->
	<el-dialog title="添加分类" width="40%" :visible.sync="dialogVisible" :close-on-click-modal="false">
		<el-form :model="dataForm" label-width="100px" :rules="dataFormRules" ref="dataForm" :size="size"
			label-position="right">
			
			<el-form-item label="分类名称:" prop="serviceTypeName">
				<el-input v-model="dataForm.serviceTypeName" auto-complete="off"></el-input>
			</el-form-item>
			<el-form-item label="分类简介:" prop="serviceTypeRemark">
				<el-input v-model="dataForm.serviceTypeRemark" auto-complete="off"></el-input>
			</el-form-item>
			<el-form-item label="分类图片:" prop="name">
					<el-upload
					ref="upload"
					action="#"
					accept="image/png,image/gif,image/jpg,image/jpeg"
					list-type="picture-card"
					:limit=limitNum
					:on-change="imageChange"
					:auto-upload="false"
					:on-exceed="handleExceed"
					:before-upload="handleBeforeUpload"
					:on-preview="handlePictureCardPreview"
					:on-remove="handleRemove" 
					:v-show="!hideShow">
					<i class="el-icon-plus"></i>
				</el-upload>																	
			</el-form-item>
			<el-form-item label="分类banner:" prop="name">
					<el-upload
					ref="upload"
					action="#"
					accept="image/png,image/gif,image/jpg,image/jpeg"
					list-type="picture-card"
					:limit=limitNum
					:on-change="imageChange1"
					:auto-upload="false"
					:on-exceed="handleExceed"
					:before-upload="handleBeforeUpload"
					:on-preview="handlePictureCardPreview"
					:on-remove="handleRemove" 
					:v-show="!hideShow">
					<i class="el-icon-plus"></i>
				</el-upload>																	
			</el-form-item>
			
			<el-form-item label="排序:" prop="subsequence">
				<el-input v-model="dataForm.subsequence" auto-complete="off"></el-input>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button :size="size" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
			<el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading">{{$t('action.submit')}}</el-button>
		</div>
	</el-dialog>
  </div>
</template>
<script>
import PopupTreeInput from "@/components/PopupTreeInput"
import KtTable from "@/views/Core/KtTable"
import KtButton from "@/views/Core/KtButton"
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog"
import { format } from "@/utils/datetime"

export default {
	components:{
		PopupTreeInput,
		KtTable,
		KtButton,
		TableColumnFilterDialog,
	},
	data() {
		return {
      		limitNum: 1,
			size: 'small',
			filters: {
				serviceTypeName: null
			},
			columns: [],
			filterColumns: [],
			pageRequest: { pageNum: 1, pageSize: 10 },
			pageResult: {"pageNum":1,"pageSize":10,"totalSize":0,"totalPages":0,"content":[]},

			operation: false, // true:新增, false:编辑
			dialogVisible: false, // 新增编辑界面是否显示
			editLoading: false,
			dataFormRules: {
				serviceTypeName: [
					{ required: true, message: '请输入服务名称', trigger: 'blur' }
				],
				file: [
					{ required: true, message: '请上传图片', trigger: 'blur' }
				],
				serviceTypeRemark: [
					{ required: true, message: '请输入服务简介', trigger: 'blur' }
				],
				subsequence: [
					{ required: true, message: '请输入排序', trigger: 'blur' }
				]
			},
			// 新增编辑界面数据
			dataForm: {
				serviceTypeName: '',
				serviceTypeRemark: '',
				file: null,
				bannerfile:null,
				subsequence: '',
				serviceTypePic:'',
				serviceTypeBanner:''
			},
		}
	},
	methods: {
		// 获取分页数据
		findPage: function (data) {
			var me = this;
			if(data !== null && data !== undefined) {
				me.pageRequest = data
			}
			console.log(me.pageRequest);
			let req = {
				"curPage":me.pageRequest.pageNum,
				"limit":me.pageRequest.pageSize,
				"serviceTypeName":me.filters.serviceTypeName
			}
			this.$api.servicetype.findPage(req).then((res) => {
				if(res.code != 200) {
					this.$message({
					message: res.msg,
					type: 'error'
					})
				} else {
					me.pageResult.pageNum = res.page.currPage;
					me.pageResult.pageSize = res.page.pageSize;
					me.pageResult.totalSize = res.page.totalCount;
					me.pageResult.totalPages = res.page.totalPage;
					me.pageResult.content = res.page.list;
					console.log(me.pageResult)
				}
			}).then(data!=null?data.callback:'')
		},
		//停用
		handleStop:function(params){
			debugger;
			var dataForm = Object.assign({}, params.row)
			console.log(dataForm);
			var status = 2;
			let req = {"id":dataForm.id,"status":status}
			this.$api.servicetype.updateStatus(req).then((res) => {
				if(res.code == 200) {
					this.$message({ message: '操作成功', type: 'success' })
				} else {
					this.$message({message: '操作失败, ' + res.msg, type: 'error'})
				}
				this.findPage(null)
			})
		},
		//启用
		handleStart:function(params){
			var dataForm = Object.assign({}, params.row)
			console.log(dataForm);
			var status = 1;
			let req = {"id":dataForm.id,"status":status}
			this.$api.servicetype.updateStatus(req).then((res) => {
				if(res.code == 200) {
					this.$message({ message: '操作成功', type: 'success' })
				} else {
					this.$message({message: '操作失败, ' + res.msg, type: 'error'})
				}
				this.findPage(null)
			})
		},
		// 显示新增界面
		handleAdd: function () {
			this.dialogVisible = true
			this.operation = true
			this.dataForm = {
				serviceTypeName: '',
				serviceTypeRemark: '',
				file: null,
				bannerfile:null,
				subsequence: '',
				serviceTypeBanner:'',
				serviceTypePic:''
			}
		},
		// 显示编辑界面
		handleEdit: function (params) {
			var me = this;
			me.operation = false
			var param = Object.assign({}, params.row)
			let req = {"id":param.id}
			debugger;
			this.$api.servicetype.findbyid(req).then((res) => {
				if(res.code != 200) {
					this.$message({
					message: res.msg,
					type: 'error'
					})
				} else {
					me.dialogVisible = true
					me.dataForm = res.hospitalServiceType;
				}
			})
		},
		// 编辑
		submitForm: function () {
			var me = this;
			this.$refs.dataForm.validate((valid) => {
				if (valid) {
					this.$confirm('确认提交吗？', '提示', {}).then(() => {
						//修改
						if(me.operation == false){
							let params = Object.assign({}, me.dataForm)
							console.log(params);
							this.$api.servicetype.update(params).then((res) => {
								if(res.code == 200) {
									this.$message({ message: '操作成功', type: 'success' })
									this.dialogVisible = false
								} else {
									this.$message({message: '操作失败, ' + res.msg, type: 'error'})
								}
								me.dataForm.file=null;
								me.dataForm.bannerfile=null;
								this.findPage(null)
							})
						}else{
							//新增	
							console.log(me.dataForm);				
							this.$api.servicetype.save(me.dataForm).then((res) => {
								if(res.code == 200) {
									this.$message({ message: '操作成功', type: 'success' })
									this.dialogVisible = false
								} else {
									this.$message({message: '操作失败, ' + res.msg, type: 'error'})
								}
								me.dataForm.file=null;
								me.dataForm.bannerfile=null;
								this.findPage(null)
							})
						}
						
					})
				}
			})
		},
		// 时间格式化
      	dateFormat: function (row, column, cellValue, index){
          	return format(row[column.property])
      	},
		//状态格式化
		stateFormat(row, column) {
			console.log(row.state)
			if (row.state === 1) {
			return '正常'
			} else if (row.state === 2) {
			return '停用'
			} 
      	},	
		// 处理表格列过滤显示
      	displayFilterColumnsDialog: function () {
			this.$refs.tableColumnFilterDialog.setDialogVisible(true)
      	},
		// 处理表格列过滤显示
      	handleFilterColumns: function (data) {
			this.filterColumns = data.filterColumns
			this.$refs.tableColumnFilterDialog.setDialogVisible(false)
      	},
		// 处理表格列过滤显示
      	initColumns: function () {
			this.columns = [
				{prop:"id", label:"编号", minWidth:50},
				{prop:"serviceTypeName", label:"分类名称", minWidth:120},
				{prop:"serviceTypeRemark", label:"分类简介", minWidth:120},
				{prop:"count", label:"服务数量", minWidth:100},
				{prop:"subsequence", label:"排序", minWidth:120},
				{prop:"status", label:"状态", minWidth:70, formatter:this.stateFormat},
			]
			this.filterColumns = JSON.parse(JSON.stringify(this.columns));
      	},
		imageChange(file, fileList) {
			console.log(file, fileList);
			if(file){
				this.uploadFile(file,1);
			}
		},
		imageChange1(file, fileList) {
			console.log(file, fileList);
			if(file){
				this.uploadFile(file,2);
			}
		},
		uploadFile(file,id) {
			debugger
			var me = this;
			let formData = new FormData()
			formData.append('file', file.raw)
			this.$api.file.upload(formData).then((res) => {
				console.log(res);
				debugger;
                if(res.code == 200) {
					if(id==1){
						me.dataForm.serviceTypePic = res.data;
					}else{
						me.dataForm.serviceTypeBanner = res.data;
					}
                    this.$message({ message: '图片上传成功', type: 'success' })
                } else {
                    this.$message({message: '图片上传失败, ' + res.msg, type: 'error'})
                }
            })
		},
		//图片上传相关方法
		handleBeforeUpload(file){
			console.log('before')
			if(!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
				this.$notify.warning({
				title: '警告',
				message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
				})
			}
			let size = file.size / 1024 / 1024 / 2
			if(size > 2) {
				this.$notify.warning({
				title: '警告',
				message: '图片大小必须小于2M'
				})
			}	
		},
		// 文件超出个数限制时的钩子
		handleExceed(files, fileList) {
			debugger;
			this.dataForm.file = file;
			if(files.length==1){
				alert("只能上传一张图片");
			}
		},
		// 文件列表移除文件时的钩子
		handleRemove(file, fileList) {
			console.log(file, fileList);
		},
		// 点击文件列表中已上传的文件时的钩子
		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.url;
			this.dialogVisible = true;
		},
		hideShow() {//当图片多于一张的时候，就隐藏上传框
			return this.files === '' ? false : true
		},
		setType(){
			this.GLOBAL.setType('4');
		}
	},
	created(){
		this.setType();
	},
	mounted() {
		this.initColumns();
		this.findPage();
		this.hideShow();
	}
}
</script>